package training.bms.business;

import java.util.Date;

import org.apache.commons.lang.ObjectUtils;

import training.bms.persistence.BlogDao;
import training.framework.business.AbstractEntityController;
import training.framework.business.BusinessException;
import training.framework.presentation.AbstractEntityDao;

public class BlogController extends AbstractEntityController<Integer, Blog, BlogSearchOptions> {
	private BlogDao dao;
	
	BlogController(BlogDao dao) {
		this.dao = dao;
	}
	
	public BlogController() {
		dao = new BlogDao();
	}

	@Override
	protected AbstractEntityDao<Integer, Blog, BlogSearchOptions> getDao() {
		return this.dao;
	}

	@Override
	protected void validateInsert(Blog entity) {
		
		validateEntity(entity);
		
		if(entity.getIdentifier() != null){
			throw new IllegalArgumentException("entity.getIdentifier() != null");
		}
		
		validateUpdate(entity);
		entity.setCreationDate(new Date());
	}

	@Override
	protected void validateUpdate(Blog entity) {
		validateEntity(entity);
		String blogName = entity.getName();
		Blog databaseBlog = dao.selectBlog(blogName);
		
		if(databaseBlog != null){
			Integer databaseBlogIdentifier = databaseBlog.getIdentifier();
			Integer blogIdentifier = entity.getIdentifier();
			
			if(ObjectUtils.notEqual(databaseBlogIdentifier, blogIdentifier)){
				throw new BusinessException("There is already a blog named");
			}
		}
	}
	
	private void validateEntity(Blog entity){
		if(entity == null){
			throw new IllegalArgumentException("entity == null");
		}
	}
	

	@Override
	protected void validateDelete(Blog entity) {}

}
